<template>
    <div class="role">
        <div class="role-data">
            <div class="role-data__filter">
                <custom-filter @onSubmit="handleInitTable" @onReset="handleResetTable" hideEnabled></custom-filter>
            </div>
            <div class="role-data__buttons">
                <yl-multi-button
                    class="multi-action"
                    :selectedRowKeys="selectedRowKeys"
                    @add="handleAddRole"
                    @multiDelete="handleMultiDelete"
                    @export="handleRoleDownload"
                    :hideAdd="true"
                    :hideExport="true"
                    :hideDelete="true"
                ></yl-multi-button>
            </div>
            <div class="role-data__table role-noBg">
                <a-table
                    :columns="columns"
                    :data-source="dataSource"
                    :row-key="setRowKey"
                    :pagination="pagination"
                    :loading="loading"
                    :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                    :scroll="{ y: 540 }"
                    class="role-data__table-table"
                    @change="handleTableChange"
                    :customRow="handleCustomRow"
                    :rowClassName="setRowClassName"
                >
                    <template v-for="item in columns" :key="item.dataIndex" v-slot:[item.slotName]>
                        <span>{{ t(`yl.${item.slotName}`) }}</span>
                    </template>
                    <template #enabled="{ record }">
                        <a-switch v-model:checked="record.enabled" />
                    </template>
                    <template #customAction="{ record }">
                        <a-button class="action-btn action-btn__edit" @click="handleEditRole(record)" type="primary" size="small">
                            <template #icon>
                                <EditOutlined />
                            </template>
                        </a-button>
                        <a-popconfirm placement="topRight" @confirm="handleDelete(record.id)">
                            <template #title>
                                <p>{{ t('yl.deleteConfirmtext') }}</p>
                            </template>
                            <a-button class="action-btn action-btn__delete" type="danger" size="small">
                                <template #icon>
                                    <Delete />
                                </template>
                            </a-button>
                        </a-popconfirm>
                    </template>
                </a-table>
                <div class="role-data__table-menu ant-col-24 ant-col-xs-24 ant-col-sm-24 ant-col-md-8 ant-col-lg-8 ant-col-xl-7">
                    <yl-treeselect-menu-vue
                        :checkedItem="checkedRole"
                        @submit="handleSubmit"
                        :loading="menusLoading"
                        @menusEdit="handleSubmitMenu"
                    ></yl-treeselect-menu-vue>
                </div>
            </div>
        </div>
        <yl-role-model
            :visible="visible"
            :loading="confirmLoading"
            :title="title"
            :role="selectedRow"
            @cancle="handleCancle"
            @submit="handleSubmit"
        ></yl-role-model>
    </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, onUnmounted, reactive, toRefs, watch } from 'vue';
import ylMultiButton from '@/components/ylMultiButton.vue';
import customFilter from '../user/components/tableFilter.vue';
import columns from './roleColumns';
import { useI18n } from 'vue-i18n';
import rolesTable from './rolesTable';
import ylRoleModel from './components/roleModel.vue';
import useDeleteRoles from './deleteRoles';
import { addRoles, editRoles, editRolsMenu, getDownload } from '@/api/system';
import { message } from 'ant-design-vue';
import { PaginationQuery } from '@/types/table';
import ylTreeselectMenuVue from '@/components/ylTreeselectMenu.vue';

export default defineComponent({
    name: 'role',
    components: {
        ylMultiButton,
        customFilter,
        ylRoleModel,
        ylTreeselectMenuVue,
    },
    setup() {
        const { t } = useI18n();
        let { tableQuery, getRolesData, selectedRowKeys, visible } = rolesTable;
        const state = reactive({
            title: computed(() => (selectedRowKeys.value.length ? t('yl.editRole') : t('yl.addRole'))),
            confirmLoading: false, // 弹窗按钮的loading
            checkedRole: null as null | NormalObj, // 单击行选中的角色 设置菜单分配的
            menusLoading: false,
            index: null as null | number,
        });

        onMounted(() => {
            getRolesData(tableQuery);
        });

        onUnmounted(() => {
            rolesTable.selectedRow.value = {};
            selectedRowKeys.value = [];
        });

        const handleInitTable = (query: PaginationQuery | TableCustomFilter) => {
            tableQuery.page = 0;
            const params = Object.assign({}, tableQuery, query);
            getRolesData(params);
        };
        const handleResetTable = () => {
            tableQuery.page = 0;
            getRolesData(tableQuery);
        };

        // 新增、编辑角色
        const handleSubmit = (role: NormalObj) => {
            state.confirmLoading = true;
            const msg = role.id ? t('yl.editSuccess') : t('yl.addSuccess');
            const realRequest = role.id ? editRoles(role) : addRoles(role);
            realRequest
                .then(() => {
                    state.confirmLoading = false;
                    message.success(msg);
                    visible.value = false;
                    const timer = setTimeout(() => {
                        handleInitTable(tableQuery);
                        clearTimeout(timer);
                    }, 500);
                })
                .catch(() => {
                    state.confirmLoading = false;
                });
        };

        // 设置行属性... 点击 鼠标滑过等
        const handleCustomRow = (record: NormalObj, index: number) => {
            return {
                onClick: () => {
                    state.index = index;
                    const { id } = record;
                    // selectedRowKeys.value = [id];
                    state.checkedRole = Object.assign({}, record);
                },
            };
        };
        // 多选时置空 checkedRole
        // watch(
        //     () => selectedRowKeys.value.length,
        //     (newValue) => {
        //         if (newValue == 1) return;
        //         state.checkedRole = null;
        //     }
        // );
        // 保存菜单分配
        const handleSubmitMenu = async (params: NormalObj) => {
            state.menusLoading = true;
            console.log(params);
            const data = {
                id: params.id,
                // menus: params.menus.map((item: any) => {
                //     return item.id;
                // }),
                menus: params.menus,
            };

            try {
                await editRolsMenu(data);
                const timer = setTimeout(() => {
                    handleInitTable(tableQuery);
                    clearTimeout(timer);
                }, 500);
            } catch (error) {}

            state.menusLoading = false;

            // const test = () => new Promise(() => {});
            // test()
            //     .then()
            //     .catch(() => {})
            //     .finally(() => {});
        };
        const setRowClassName = (record: NormalObj, index: number) => {
            return index === state.index ? 'clickRowStyl' : '';
        };
        // 导出角色数据
        const handleRoleDownload = () => {
            let name = t('yl.roleMgt');
            getDownload('/api/roles/download', name);
        };
        return {
            handleInitTable,
            handleResetTable,
            columns,
            t,
            ...rolesTable,
            handleSubmit,
            ...toRefs(state),
            ...useDeleteRoles(),
            handleCustomRow,
            handleSubmitMenu,
            setRowClassName,
            handleRoleDownload,
        };
    },
});
</script>

<style lang="scss" scoped>
.role {
    @include flex;
    width: 100%;
    &-dopt {
        flex-basis: 400px;
    }
    &-data {
        flex: 1;
        padding-right: $width20;
        &__filter {
            @include flex;
            &-item {
                margin-right: $width20;
            }
        }
        &__buttons {
            padding-top: $width20;
        }
        &__table {
            @include flex;
            &-table {
                flex: 1;
                margin-right: $width10;
                .action-btn + .action-btn {
                    margin-left: $width8;
                }
            }
            &-menu {
                position: relative;
                box-sizing: border-box;
                padding: 0 $width20;
                @include border();
                max-height: 570px;
                overflow: auto;
            }
        }
    }
}
</style>
<style>
.clickRowStyl {
    background: #e6f7ff;
}
.role-noBg .ant-table-tbody > tr.ant-table-row-selected td {
    background: none;
}
</style>
